package mspbots.cw.data.core.boards;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

;

/**
 * BoardReceiver is com.mspbots.cw.amqp.receivers
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/24
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class BoardsReceiver extends AbstractToolsUtil {

    private final BoardsRepository boardsRepository;

    @RabbitListener(queues = "connect-wise.boards.sync")
    public void processMsg(ResultMsg resultMsg) {

        Boards data = Boards.builder().otherId(resultMsg.getId()).build();
        data.setTenantId(resultMsg.getTenantId());
        data.setExtend(resultMsg.getEntity());
        data.setSyncTime(resultMsg.getSyncDate());

        data.setUpdateTime(ObjectUtils.isEmpty(resultMsg.getEntity().findValue("lastUpdated")) ? LocalDateTime.now() :
                LocalDateTime.parse(resultMsg.getEntity().findValue("lastUpdated").asText(),
                        DateTimeFormatter.ISO_ZONED_DATE_TIME));

        data.setCreateTime(ObjectUtils.isEmpty(resultMsg.getEntity().findValue("dateEntered")) ? LocalDateTime.now() :
                LocalDateTime.parse(resultMsg.getEntity().findValue("dateEntered").asText(),
                        DateTimeFormatter.ISO_ZONED_DATE_TIME));

        this.boardsRepository.findByOtherIdAndTenantId(resultMsg.getId(), resultMsg.getTenantId())
                .switchIfEmpty(this.boardsRepository.save(data))
                .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .flatMap(this.boardsRepository::save).block(Duration.ofSeconds(10));

    }
}
